package com.agent.controller;

import com.agent.AiService.AgentService;
import com.agent.utils.UserContext;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import reactor.core.publisher.Flux;

import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

@Tag(name = "智能助手")
@RestController
@RequestMapping("/agent")
@RequiredArgsConstructor
public class AgentController {

    // 构造函数注入
    private final AgentService Agent;

    @GetMapping(value = "/chat", produces = "text/stream;charset=utf-8")
    // produces参数，指定接口返回的是 UTF-8 编码的文本流
    // @Operation(summary = "314寝室智能对话")
    public StreamingResponseBody chat(Long memoryId, String message, HttpServletRequest request, HttpServletResponse response){
        System.out.println("memoryId：" + memoryId + " message：" + message);
        // 提示浏览器/代理不要缓存，尽快传输分块
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/stream;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("X-Accel-Buffering", "no"); // Nginx 禁用缓冲

        Long userId = (Long) request.getAttribute("userId");
        Flux<String> stream = Agent.chat(memoryId, message, userId);

        return outputStream -> {
            OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
            try {
                // 发送心跳/前导分块，触发浏览器尽快渲染
                writer.write(" ");
                writer.flush();
                try { response.flushBuffer(); } catch (Exception ignored) { }

                for (String chunk : stream.toIterable()) {
                    writer.write(chunk);
                    writer.flush(); // 逐块刷新
                    try { response.flushBuffer(); } catch (Exception ignored) { }
                }
            } catch (Exception e) {
                try {
                    writer.write("\n[ERROR] " + e.getMessage() + "\n");
                } catch (Exception ignored) { }
            } finally {
                try { writer.flush(); } catch (Exception ignored) { }
            }
        };
    }
}

